<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>User Management - CarbonTrack</title>
  <link rel="icon" href="/img/team.jpg" type="image/JPG">
  <!-- Dependencies -->
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
  <script src="js/jquery.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/utils.js"></script>
  <script src="js/nav.js"></script>
  <!-- SF Pro font -->
  <link href="https://fonts.cdnfonts.com/css/sf-pro-display" rel="stylesheet">
  <!-- Custom CSS -->
  <link rel="stylesheet" href="./css/ios-design.css">
  <link rel="stylesheet" href="./css/index.css">
  <style>
    /* Modern Header Styles */
    .admin-header {
      background: linear-gradient(125deg, #0066ff, #5933aa, #a12ddf);
      color: white;
      padding: 70px 0 60px;
      text-align: center;
      border-radius: 0 0 30px 30px;
      margin-bottom: 40px;
      position: relative;
      overflow: hidden;
      box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    }

    /* Enhanced shimmer effect */
    .admin-header::before {
      content: '';
      position: absolute;
      top: -100%;
      left: -100%;
      width: 300%;
      height: 300%;
      background: linear-gradient(
        0deg,
        rgba(255, 255, 255, 0) 0%,
        rgba(255, 255, 255, 0.03) 25%,
        rgba(255, 255, 255, 0.05) 50%,
        rgba(255, 255, 255, 0.03) 75%,
        rgba(255, 255, 255, 0) 100%
      );
      transform: rotate(25deg);
      animation: shimmer 15s infinite linear;
      pointer-events: none;
    }
    
    @keyframes shimmer {
      0% { transform: translateX(-50%) rotate(0deg); }
      100% { transform: translateX(0%) rotate(360deg); }
    }
    
    .admin-header h1 { 
      font-weight: 800; 
      margin-bottom: 16px; 
      letter-spacing: -0.5px;
      position: relative;
      z-index: 2;
      font-size: 3.2rem;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .admin-header p { 
      opacity: 0.9; 
      max-width: 600px; 
      margin: 0 auto; 
      font-size: 1.25rem; 
      position: relative;
      z-index: 2;
      font-weight: 300;
    }

    /* User Management Specific Styles - Enhanced */
    .page-container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
    }
    
    .table-container {
      background-color: var(--ios-secondary-system-background);
      padding: 28px;
      border-radius: 24px;
      box-shadow: 0 8px 30px rgba(0,0,0,0.06);
      transition: all 0.3s ease;
      overflow: hidden;
      position: relative;
      margin-bottom: 40px;
    }
    
    .table-container::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 6px;
      background: linear-gradient(90deg, #0066ff, #5933aa, #a12ddf);
      border-radius: 24px 24px 0 0;
    }
    
    .table-container:hover {
      transform: translateY(-3px);
      box-shadow: 0 14px 40px rgba(0,0,0,0.08);
    }
    
    .table {
      margin-bottom: 0;
      width: 100%;
    }
    
    .table th {
        border-top: none;
        font-weight: 600;
        color: var(--ios-secondary-label);
        text-transform: uppercase;
        font-size: 0.8rem;
        letter-spacing: 0.5px;
        padding: 16px 12px;
    }
    
    .table td {
        vertical-align: middle;
        border-top: 1px solid var(--ios-separator);
        padding: 18px 12px;
        transition: background-color 0.2s ease;
        font-size: 0.95rem;
    }
    
    .table tbody tr {
        transition: all 0.2s ease;
    }
    
    .table tbody tr:hover {
        background-color: rgba(0, 102, 255, 0.05);
    }
    
    .table tbody tr:first-child td {
        border-top: none;
    }
    
    .action-btns {
        display: flex;
        gap: 8px;
    }
    
    .action-btn {
        font-size: 0.85rem;
        padding: 8px 16px;
        border-radius: 12px;
        transition: all 0.25s ease;
        display: flex;
        align-items: center;
        gap: 6px;
        font-weight: 500;
    }
    
    .edit-btn {
        color: #0066ff;
        border-color: #0066ff;
        background-color: rgba(0, 102, 255, 0.08);
    }
    
    .edit-btn:hover {
        background-color: #0066ff;
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 4px 10px rgba(0, 102, 255, 0.2);
    }
    
    .delete-btn {
        color: #FF3B30;
        border-color: #FF3B30;
        background-color: rgba(255, 59, 48, 0.08);
    }
    
    .delete-btn:hover {
        background-color: #FF3B30;
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 4px 10px rgba(255, 59, 48, 0.2);
    }
    
    .search-container {
        margin-bottom: 30px;
        position: relative;
        max-width: 800px;
        margin-left: auto;
        margin-right: auto;
    }
    
    .search-bar {
        position: relative;
        margin-bottom: 25px;
    }
    
    .search-bar input {
        padding: 16px 50px;
        height: auto;
        border-radius: 20px;
        background-color: var(--ios-secondary-system-background);
        border: none;
        font-size: 1.05rem;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
        width: 100%;
    }
    
    .search-bar input:focus {
        background-color: var(--ios-system-background, white);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
        transform: translateY(-2px);
        border: none;
        outline: none;
    }
    
    .search-bar .fa-search {
        position: absolute;
        left: 20px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--ios-gray);
        font-size: 18px;
    }
    
    /* User stats cards - enhanced */
    .stats-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        margin-bottom: 35px;
    }
    
    .stat-card {
        background: var(--ios-secondary-system-background);
        border-radius: 20px;
        padding: 25px;
        box-shadow: 0 6px 18px rgba(0,0,0,0.06);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        height: 100%;
    }
    
    .stat-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    }
    
    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 6px;
        z-index: 1;
    }
    
    .stat-card.users::before {
        background: linear-gradient(90deg, #0066ff, #1C84FF);
    }
    
    .stat-card.points::before {
        background: linear-gradient(90deg, #30D158, #5AF97B);
    }
    
    .stat-card.schools::before {
        background: linear-gradient(90deg, #FF9500, #FFCC00);
    }
    
    .stat-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 60px;
        height: 60px;
        border-radius: 16px;
        margin-bottom: 15px;
        font-size: 24px;
    }
    
    .stat-card.users .stat-icon {
        color: white;
        background: linear-gradient(135deg, #0066ff, #1C84FF);
        box-shadow: 0 4px 12px rgba(0, 102, 255, 0.2);
    }
    
    .stat-card.points .stat-icon {
        color: white;
        background: linear-gradient(135deg, #30D158, #5AF97B);
        box-shadow: 0 4px 12px rgba(48, 209, 88, 0.2);
    }
    
    .stat-card.schools .stat-icon {
        color: white;
        background: linear-gradient(135deg, #FF9500, #FFCC00);
        box-shadow: 0 4px 12px rgba(255, 149, 0, 0.2);
    }
    
    .stat-value {
        font-size: 2.5rem;
        font-weight: 700;
        margin: 10px 0;
        background: linear-gradient(90deg, #0066ff, #5933aa);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .stat-label {
        color: var(--ios-secondary-label);
        font-size: 1rem;
        font-weight: 500;
        margin-top: auto;
    }

    /* Improved loading spinner */
    #loadingUsers {
        padding: 50px;
    }
    
    .loading-spinner {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    .loading-spinner .spinner-border {
        color: #0066ff;
        width: 3rem;
        height: 3rem;
        margin-bottom: 1.5rem;
    }
    
    .loading-text {
        color: var(--ios-secondary-label);
        font-weight: 500;
        font-size: 1.1rem;
    }

    /* Dark mode table adjustments */
     body.dark-theme .table-container, body.auto-theme.dark-mode .table-container {
        background-color: rgba(44, 44, 46, 0.8);
        box-shadow: 0 8px 30px rgba(0,0,0,0.18);
     }
     
     body.dark-theme .stat-card, body.auto-theme.dark-mode .stat-card {
        background-color: rgba(44, 44, 46, 0.8);
     }
     
     body.dark-theme .table th, body.auto-theme.dark-mode .table th {
        color: var(--ios-secondary-label-dark, #8E8E93);
     }
     
     body.dark-theme .table td, body.auto-theme.dark-mode .table td {
        border-top: 1px solid var(--ios-separator-dark, #38383A);
        color: var(--ios-label-dark, #F2F2F7);
     }
     
     body.dark-theme .table tbody tr:hover, body.auto-theme.dark-mode .table tbody tr:hover {
        background-color: rgba(10, 132, 255, 0.1);
     }
     
     body.dark-theme .search-bar input, body.auto-theme.dark-mode .search-bar input {
         background-color: rgba(44, 44, 46, 0.8);
         border-color: var(--ios-separator-dark, #38383A);
         color: var(--ios-label-dark, #F2F2F7);
     }
     
     body.dark-theme .search-bar input:focus, body.auto-theme.dark-mode .search-bar input:focus {
         background-color: rgba(58, 58, 60, 0.9);
     }
     
     body.dark-theme .search-bar .fa-search, body.auto-theme.dark-mode .search-bar .fa-search {
         color: var(--ios-secondary-label-dark, #8E8E93);
     }
     
     /* Improved modal styling */
     .ios-modal-content {
         border-radius: 24px;
         border: none;
         box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
         overflow: hidden;
     }
     
     .ios-modal-header {
         padding: 24px 28px;
         border-bottom: 1px solid var(--ios-separator);
         position: relative;
     }
     
     .ios-modal-header .modal-title {
         font-weight: 700;
         font-size: 1.4rem;
         color: var(--ios-label);
     }
     
     .ios-modal-header .close {
         opacity: 0.6;
         transition: opacity 0.2s ease;
         font-size: 1.5rem;
     }
     
     .ios-modal-header .close:hover {
         opacity: 1;
     }
     
     .ios-modal-body {
         padding: 28px;
     }
     
     .ios-modal-footer {
         padding: 20px 28px 28px;
         border-top: none;
     }
     
     .form-group label {
         font-weight: 600;
         color: var(--ios-secondary-label);
         margin-bottom: 8px;
         font-size: 0.9rem;
     }
     
     .form-control-static {
         font-size: 1.1rem;
         padding: 12px;
         background: rgba(0, 0, 0, 0.03);
         border-radius: 12px;
         margin-bottom: 15px;
     }
     
     .ios-input {
         border-radius: 12px;
         padding: 12px 16px;
         border: 1px solid var(--ios-separator);
         transition: all 0.3s ease;
         font-size: 1rem;
         height: auto;
     }
     
     .ios-input:focus {
         border-color: #0066ff;
         box-shadow: 0 0 0 3px rgba(0, 102, 255, 0.2);
     }
     
     /* Modal buttons */
     .modal-footer .btn {
         padding: 12px 24px;
         border-radius: 12px;
         font-weight: 600;
         transition: all 0.3s ease;
     }
     
     .modal-footer .btn-primary {
         background: linear-gradient(to right, #0066ff, #5933aa);
         border: none;
     }
     
     .modal-footer .btn-primary:hover {
         transform: translateY(-2px);
         box-shadow: 0 6px 15px rgba(0, 102, 255, 0.3);
     }
     
     .modal-footer .btn-secondary {
         background-color: rgba(0, 0, 0, 0.05);
         border: none;
         color: var(--ios-label);
     }
     
     .modal-footer .btn-secondary:hover {
         background-color: rgba(0, 0, 0, 0.1);
     }
     
     body.dark-theme .ios-modal-content, body.auto-theme.dark-mode .ios-modal-content {
         background-color: rgba(44, 44, 46, 0.95);
     }
     
     body.dark-theme .ios-modal-header, body.auto-theme.dark-mode .ios-modal-header {
         border-bottom-color: var(--ios-separator-dark, #38383A);
     }
     
     body.dark-theme .form-control-static, body.auto-theme.dark-mode .form-control-static {
         background: rgba(255, 255, 255, 0.05);
     }
     
     body.dark-theme .ios-input, body.auto-theme.dark-mode .ios-input {
         background-color: rgba(255, 255, 255, 0.1);
         border-color: var(--ios-separator-dark, #38383A);
         color: var(--ios-label-dark, #F2F2F7);
     }
     
     body.dark-theme .ios-input:focus, body.auto-theme.dark-mode .ios-input:focus {
         border-color: #0066ff;
         background-color: rgba(255, 255, 255, 0.15);
     }
     
     body.dark-theme .modal-footer .btn-secondary, body.auto-theme.dark-mode .modal-footer .btn-secondary {
         background-color: rgba(255, 255, 255, 0.1);
         color: var(--ios-label-dark, #F2F2F7);
     }
     
     /* Animation for fade-in effects */
     @keyframes fadeInUp {
         from {
             opacity: 0;
             transform: translateY(20px);
         }
         to {
             opacity: 1;
             transform: translateY(0);
         }
     }
     
     @keyframes scaleIn {
         from {
             opacity: 0;
             transform: scale(0.95);
         }
         to {
             opacity: 1;
             transform: scale(1);
         }
     }
     
     .fade-in {
         animation: fadeInUp 0.5s ease-out forwards;
     }
     
     .scale-in {
         animation: scaleIn 0.4s ease-out forwards;
     }
     
     .delay-1 { animation-delay: 0.1s; }
     .delay-2 { animation-delay: 0.2s; }
     .delay-3 { animation-delay: 0.3s; }
     .delay-4 { animation-delay: 0.4s; }
     
     /* Responsive adjustments */
     @media (max-width: 992px) {
         .stats-container {
             grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
         }
         
         .admin-header h1 {
             font-size: 2.5rem;
         }
     }
     
     @media (max-width: 768px) {
         .table-container {
             padding: 20px 15px;
             border-radius: 18px;
         }
         
         .admin-header {
             padding: 50px 0 40px;
         }
         
         .admin-header h1 {
             font-size: 2rem;
         }
         
         .admin-header p {
             font-size: 1rem;
         }
         
         .search-bar input {
             padding: 14px 45px;
         }
         
         .action-btn {
             padding: 6px 12px;
             font-size: 0.8rem;
         }
     }
     
     @media (max-width: 576px) {
         .stats-container {
             grid-template-columns: 1fr;
         }
         
         .stat-card {
             margin-bottom: 15px;
         }
     }

    /* ----- Add Dark Mode Styles ----- */
    body.dark-theme {
        background-color: var(--ios-system-background-dark);
        color: var(--ios-label-dark);
    }

    body.dark-theme .admin-header {
        /* Gradient might need slight adjustment for dark, or keep as is */
    }

    body.dark-theme .table-container {
        background-color: var(--ios-tertiary-system-background-dark); /* Use tertiary for table container */
        box-shadow: 0 8px 30px rgba(0,0,0,0.2);
    }
    body.dark-theme .table-container::after {
        /* Keep the gradient for the top bar */
    }

    body.dark-theme .table th {
        color: var(--ios-secondary-label-dark);
        border-top: none; /* Keep this */
    }

    body.dark-theme .table td {
        border-top: 1px solid var(--ios-separator-dark);
        color: var(--ios-label-dark);
    }

    body.dark-theme .table tbody tr:hover {
        background-color: rgba(10, 132, 255, 0.15); /* Slightly more visible hover */
    }

    body.dark-theme .search-bar input {
        background-color: var(--ios-tertiary-system-background-dark);
        color: var(--ios-label-dark);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
    }
    body.dark-theme .search-bar input::placeholder {
        color: var(--ios-secondary-label-dark);
    }
    body.dark-theme .search-bar input:focus {
        background-color: var(--ios-secondary-system-background-dark);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
    }
    body.dark-theme .search-bar .fa-search {
        color: var(--ios-gray-dark);
    }

    body.dark-theme .stat-card {
        background: var(--ios-tertiary-system-background-dark);
        box-shadow: 0 6px 18px rgba(0,0,0,0.2);
        color: var(--ios-label-dark);
    }
    body.dark-theme .stat-label {
         color: var(--ios-secondary-label-dark);
    }
    body.dark-theme .stat-value {
         /* Rely on main label color or adjust if needed */
    }

     /* Edit/Delete buttons in dark mode */
     body.dark-theme .edit-btn {
        color: #0A84FF; /* iOS Blue Dark */
        border-color: #0A84FF;
        background-color: rgba(10, 132, 255, 0.15);
    }
    body.dark-theme .edit-btn:hover {
        background-color: #0A84FF;
        color: white;
        box-shadow: 0 4px 10px rgba(10, 132, 255, 0.3);
    }
    body.dark-theme .delete-btn {
        color: #FF453A; /* iOS Red Dark */
        border-color: #FF453A;
        background-color: rgba(255, 69, 58, 0.15);
    }
    body.dark-theme .delete-btn:hover {
        background-color: #FF453A;
        color: white;
        box-shadow: 0 4px 10px rgba(255, 69, 58, 0.3);
    }

    /* Pagination */
    body.dark-theme .pagination .page-link {
        background-color: var(--ios-tertiary-system-background-dark);
        border-color: var(--ios-separator-dark);
        color: var(--ios-blue-dark);
    }
     body.dark-theme .pagination .page-link:hover {
        background-color: rgba(10, 132, 255, 0.15);
    }
    body.dark-theme .pagination .page-item.disabled .page-link {
        background-color: var(--ios-tertiary-system-background-dark);
        border-color: var(--ios-separator-dark);
        color: var(--ios-secondary-label-dark);
    }
     body.dark-theme .pagination .page-item.active .page-link {
        background-color: var(--ios-blue-dark);
        border-color: var(--ios-blue-dark);
        color: white;
    }

     /* Theme Toggle Button */
    #theme-toggle-button {
      position: fixed;
      bottom: 20px;
      right: 20px;
      background-color: var(--button-bg-light, #fff);
      color: var(--button-text-light, #333);
      border: 1px solid var(--border-color-light, #ccc);
      border-radius: 50%;
      width: 45px;
      height: 45px;
      font-size: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      z-index: 1050;
      transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease, transform 0.2s ease;
      box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }

    body.dark-theme #theme-toggle-button {
      background-color: var(--button-bg-dark, #333);
      color: var(--button-text-dark, #fff);
      border: 1px solid var(--border-color-dark, #555);
      box-shadow: 0 2px 5px rgba(255,255,255,0.15);
    }
    #theme-toggle-button:hover {
        transform: scale(1.05);
        opacity: 0.9;
    }

  </style>
</head>
<body class="auto-theme">

<!-- Theme Toggle Button HTML -->
<button id="theme-toggle-button" aria-label="Toggle theme">
  <i class="fas fa-sun"></i> <!-- Default icon -->
</button>

<!-- 导航栏容器，将由JavaScript加载 -->
<div id="navbar-container"></div>

<header class="admin-header">
  <div class="container">
    <h1>User Management</h1>
    <p>View, search, and manage user accounts on the CarbonTrack platform.</p>
  </div>
</header>

<!-- User Management Content -->
<div class="page-container">
  <!-- User Stats -->
  <div class="stats-container">
    <div class="stat-card users scale-in delay-1">
      <div class="stat-icon">
        <i class="fas fa-user"></i>
      </div>
      <p class="stat-value" id="totalUsers">-</p>
      <p class="stat-label">Total Users</p>
    </div>
    <div class="stat-card points scale-in delay-2">
      <div class="stat-icon">
        <i class="fas fa-award"></i>
      </div>
      <p class="stat-value" id="totalPoints">-</p>
      <p class="stat-label">Total Carbon Credits</p>
    </div>
    <div class="stat-card schools scale-in delay-3">
      <div class="stat-icon">
        <i class="fas fa-university"></i>
      </div>
      <p class="stat-value" id="totalSchools">-</p>
      <p class="stat-label">Schools</p>
    </div>
  </div>

  <!-- Search Bar -->
  <div class="search-container fade-in delay-2">
    <div class="search-bar">
      <i class="fas fa-search"></i>
      <input type="text" id="userSearchInput" class="form-control" placeholder="Search by username or email...">
    </div>
  </div>

  <div class="table-container fade-in delay-3">
    <!-- User Table -->
    <div class="table-responsive">
      <table class="table table-hover">
        <thead>
          <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Points</th>
            <th>School</th>
            <th>Last Login</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody id="userTableBody">
          <!-- User data will be loaded here by JavaScript -->
          <tr>
            <td colspan="7" class="text-center" id="loadingUsers">
              <div class="loading-spinner">
                <div class="spinner-border" role="status">
                  <span class="sr-only">Loading...</span>
                </div>
                <span class="loading-text">Loading users...</span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Footer -->
<div id="footer-placeholder"></div>

<!-- Edit User Modal (Example Structure) -->
<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content ios-modal-content">
      <div class="modal-header ios-modal-header">
        <h5 class="modal-title">Edit User</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body ios-modal-body">
        <form id="editUserForm">
          <input type="hidden" id="editUserId">
          <div class="form-group">
            <label>Username:</label>
            <p id="editUsername" class="form-control-static"></p> <!-- Display only -->
          </div>
          <div class="form-group">
            <label>Email:</label>
            <p id="editUserEmail" class="form-control-static"></p> <!-- Display only -->
          </div>
          <div class="form-group">
            <label for="editUserPoints">Points:</label>
            <input type="number" class="form-control ios-input" id="editUserPoints" step="0.01" required>
          </div>
          <div class="form-group">
            <label for="editUserSchool">School:</label>
            <input type="text" class="form-control ios-input" id="editUserSchool">
          </div>
        </form>
      </div>
      <div class="modal-footer ios-modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="saveUserChangesBtn">Save Changes</button>
      </div>
    </div>
  </div>
</div>


<script>
  $(document).ready(function() {
    // Admin check
    var token = localStorage.getItem('token');
    if (!token) {
      showAlert('Please log in first.', 'warning', () => { window.location.href = 'index.html'; });
      return;
    }
    checkAdminAccess(token); // This will load users if successful

    // Search functionality (debounced)
    let searchTimeout;
    $('#userSearchInput').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            fetchUsers(token, $(this).val());
        }, 300); // Debounce time
    });

    // --- Event delegation for dynamically loaded buttons ---

    // Edit button click
    $('#userTableBody').on('click', '.edit-btn', function() {
        const userId = $(this).data('id');
        const userRow = $(this).closest('tr');
        // Populate modal
        $('#editUserId').val(userId);
        $('#editUsername').text(userRow.find('td:eq(1)').text());
        $('#editUserEmail').text(userRow.find('td:eq(2)').text());
        $('#editUserPoints').val(userRow.find('td:eq(3)').text());
        $('#editUserSchool').val(userRow.find('td:eq(4)').text());
        $('#editUserModal').modal('show');
    });

    // Save changes button click
    $('#saveUserChangesBtn').on('click', function() {
        const userId = $('#editUserId').val();
        const points = $('#editUserPoints').val();
        const school = $('#editUserSchool').val();
        updateUser(token, userId, points, school);
    });

    // Delete button click
    $('#userTableBody').on('click', '.delete-btn', function() {
        const userId = $(this).data('id');
        const username = $(this).closest('tr').find('td:eq(1)').text();
        
        // Use the showAlert function for a more iOS-like confirmation
        showAlert(`Are you sure you want to deactivate user "${username}" (ID: ${userId})? The account will no longer be able to sign in.`, 'warning', function() {
            deleteUser(token, userId);
        });
    });
  });

  function checkAdminAccess(token) {
    $.ajax({
      url: 'verify_admin.php', type: 'POST', data: { token: token }, dataType: 'json',
      success: function(response) {
        if (!response.success || !response.isAdmin) {
          showAlert('Admin access required.', 'error', () => { window.location.href = 'index.html'; });
        } else {
          fetchUsers(token); // Load initial user list
        }
      },
      error: function() {
        showAlert('Permission check failed. Please try again.', 'error', () => { window.location.href = 'index.html'; });
      }
    });
  }

  function fetchUsers(token, searchTerm = '') {
      $('#loadingUsers').show();
      $('#userTableBody').find('tr:not(:first)').remove(); // Clear previous users except loading row

      $.ajax({
          url: 'get_users.php', type: 'POST',
          data: { token: token, search: searchTerm },
          dataType: 'json',
          success: function(response) {
              $('#loadingUsers').hide();
              if (response.success) {
                  if (response.users && response.users.length > 0) {
                      displayUsers(response.users);
                      updateStatistics(response.users);
                  } else {
                      $('#userTableBody').append('<tr><td colspan="7" class="text-center">No users found matching your search.</td></tr>');
                      // Reset statistics for empty results
                      $('#totalUsers').text('0');
                      $('#totalPoints').text('0');
                      $('#totalSchools').text('0');
                  }
              } else {
                  showAlert(response.message || 'Failed to load users.', 'error');
                   $('#userTableBody').append(`<tr><td colspan="7" class="text-center text-danger">Error: ${response.message || 'Could not load users.'}</td></tr>`);
              }
          },
          error: function() {
              $('#loadingUsers').hide();
              showAlert('Failed to connect to server to fetch users.', 'error');
              $('#userTableBody').append('<tr><td colspan="7" class="text-center text-danger">Server connection error.</td></tr>');
          }
      });
  }

  function displayUsers(users) {
      const tableBody = $('#userTableBody');
      tableBody.empty(); // Clear loading/previous content

      users.forEach((user, index) => {
          // Format last login - assuming it's a string like 'YYYY-MM-DD HH:MM:SS' or null
          let lastLoginFormatted = user.lastlgn ? formatDateTime(user.lastlgn) : 'Never';

          // Add animation delay class based on row index
          const delayClass = index < 10 ? `delay-${index % 5}` : '';
          
          const row = `
              <tr class="fade-in ${delayClass}">
                  <td>${user.id}</td>
                  <td>${escapeHtml(user.username)}</td>
                  <td>${escapeHtml(user.email)}</td>
                  <td>${user.points ? parseFloat(user.points).toFixed(2) : '0.00'}</td>
                  <td>${escapeHtml(user.school || '-')}</td>
                  <td>${lastLoginFormatted}</td>
                  <td>
                      <div class="action-btns">
                          <button class="btn btn-sm action-btn edit-btn" data-id="${user.id}"><i class="fas fa-edit"></i> Edit</button>
                          <button class="btn btn-sm action-btn delete-btn" data-id="${user.id}"><i class="fas fa-user-slash"></i> Deactivate</button>
                      </div>
                  </td>
              </tr>
          `;
          tableBody.append(row);
      });
  }

  function updateStatistics(users) {
      // Total users
      $('#totalUsers').text(users.length);
      
      // Total points
      const totalPoints = users.reduce((sum, user) => {
          return sum + (parseFloat(user.points) || 0);
      }, 0);
      $('#totalPoints').text(totalPoints.toFixed(2));
      
      // Total unique schools
      const uniqueSchools = new Set();
      users.forEach(user => {
          if (user.school && user.school.trim() !== '') {
              uniqueSchools.add(user.school.trim());
          }
      });
      $('#totalSchools').text(uniqueSchools.size);
  }

  function updateUser(token, userId, points, school) {
      // Show updating indicator on button
      const saveBtn = $('#saveUserChangesBtn').html('<i class="fas fa-spinner fa-spin"></i> Saving...');
      saveBtn.prop('disabled', true);
      
      $.ajax({
          url: 'update_user.php', type: 'POST',
          data: { token: token, userId: userId, points: points, school: school },
          dataType: 'json',
          success: function(response) {
              if (response.success) {
                  showAlert('User updated successfully!', 'success');
                  $('#editUserModal').modal('hide');
                  fetchUsers(token, $('#userSearchInput').val()); // Refresh list with current search
              } else {
                  showAlert(response.message || 'Failed to update user.', 'error');
              }
              // Reset button state
              saveBtn.html('Save Changes').prop('disabled', false);
          },
          error: function() {
              showAlert('Failed to connect to server to update user.', 'error');
              // Reset button state
              saveBtn.html('Save Changes').prop('disabled', false);
          }
      });
  }

  function deleteUser(token, userId) {
      $.ajax({
          url: 'delete_user.php', type: 'POST',
          data: { token: token, userId: userId },
          dataType: 'json',
          success: function(response) {
              if (response.success) {
                  showAlert('User deactivated successfully!', 'success');
                  fetchUsers(token, $('#userSearchInput').val()); // Refresh list
              } else {
                  showAlert(response.message || 'Failed to deactivate user.', 'error');
              }
          },
          error: function() {
              showAlert('Failed to connect to server to deactivate user.', 'error');
          }
      });
  }

  // Simple HTML escaping function
  function escapeHtml(text) {
      if (text === null || text === undefined) return '';
      return String(text)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;')
          .replace(/'/g, '&#039;');
  }

  // Format date-time for display
  function formatDateTime(dateStr) {
      try {
          const date = new Date(dateStr);
          if (isNaN(date)) return dateStr; // Return as-is if invalid
          
          return new Intl.DateTimeFormat('en-US', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              hour12: true
          }).format(date);
      } catch (e) {
          return dateStr; // Return as-is if any error occurs
      }
  }

  // Theme toggling logic
  const themeToggleButton = document.getElementById('theme-toggle-button');
  const currentTheme = localStorage.getItem('theme') || 'auto'; // Default to 'auto'

  function applyTheme(theme) {
    const body = document.body;
    const icon = themeToggleButton.querySelector('i');
    body.classList.remove('light-theme', 'dark-theme'); // Remove existing theme classes

    if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      body.classList.add('dark-theme');
      icon.className = 'fas fa-moon'; // Moon icon for dark
    } else {
      body.classList.add('light-theme'); // Explicitly add light-theme or rely on default
      icon.className = 'fas fa-sun'; // Sun icon for light
    }
    localStorage.setItem('theme', theme);

     // Update icon for auto based on effective theme
    if (theme === 'auto') {
        icon.className = 'fas fa-adjust'; // Use adjust icon for auto
    }
  }

  function cycleTheme() {
    const themes = ['light', 'dark', 'auto'];
    let currentThemeIndex = themes.indexOf(localStorage.getItem('theme') || 'auto');
    let nextThemeIndex = (currentThemeIndex + 1) % themes.length;
    applyTheme(themes[nextThemeIndex]);
  }

  // Apply initial theme on load
  applyTheme(currentTheme);

  // Listen for system theme changes if in 'auto' mode
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
    if (localStorage.getItem('theme') === 'auto') {
      applyTheme('auto');
    }
  });

  // Add event listener to the button
  themeToggleButton.addEventListener('click', cycleTheme);

</script>

</body>
</html> 